// 存储所有连接的端口
const ports = [];
let socket;

// 当页面连接时触发
self.onconnect = (e) => {
  const port = e.ports[0];
  ports.push(port);

  // 初始化 WebSocket（仅首次连接时）
  if (!socket) {

    initWebSocket();

    function initWebSocket() {
        // WebSocket URL, replace with your server's WebSocket endpoint
        const wsURL = 'ws://127.0.0.1:2121/ws'; // Replace with actual URL

        socket = new WebSocket(wsURL);

        // Connection opened
        socket.addEventListener('open', onOpen);

        // Listen for messages
        socket.addEventListener('message', onMessage);

        // Listen for errors
        socket.addEventListener('error', onError);

        // Connection closed
        socket.addEventListener('close', onClose);
    }

    function onOpen(event) {
        console.log('已连接到WebSocket服务器。');
        //document.getElementById('status').innerText = '已连接到WebSocket服务器。';
        // Send login message or token here
        const loginData = {
            user_code: 'user',
            user_key: 'user_key', // Replace with actual user data
            server_password: 'myServerPassword'  // Replace with actual user data or use a token instead
        };

        socket.send(JSON.stringify(loginData));
    }

    function onMessage(event) {
        console.log('来自服务器的消息 ', event.data);


        // 广播消息给所有页面
        ports.forEach(p => p.postMessage({"type":"msg","data":event.data}));

        // Parse the incoming message and handle it accordingly
        // try {
        //     const data = JSON.parse(event.data);
        //     console.log(data)
        //     if(data.message == 'Login successful'){
        //         document.getElementById('status').innerText = '登录成功.';
        //     }else{
        //         displayNewMessage(data);
        //     }

        // } catch (e) {
        //     console.error('解析消息失败：', e);
        // }


    }

    function onError(event) {
        //document.getElementById('status').innerText = '观察到WebSocket错误：' + event;
        console.error('观察到WebSocket错误：', event);
    }

    function onClose(event) {
        console.log('WebSocket连接已关闭。正在尝试重新连接。。。');
        //document.getElementById('status').innerText = 'WebSocket连接已关闭。正在尝试重新连接。。。';
        // Optionally, you can check the event.code to determine why the connection was closed
        
        // Attempt to reconnect after a delay
        setTimeout(initWebSocket, 5000); // Retry every 5 seconds
    }


  }else{
    //广播消息给所有页面登录了
    ports.forEach(p => p.postMessage({"type":"on","data":'ok'}));
  }

  // 接收来自页面的消息
  port.onmessage = (e) => {
      console.log("页面",e.data)
       if (e.data.type === 'close') {
            const index = ports.indexOf(port);
            ports.splice(index, 1);
            return;
        }
  };
  
    setInterval(() => {
      ports.forEach(p => p.postMessage({"type":"ping","data":'1'}));
    }, 30000); // 每30秒发送心跳

};
